package handling.login.handler;

import client.MapleClient;
import constants.ServerConstants;
import database.DatabaseConnection;
import handling.login.LoginServer;
import handling.login.LoginWorker;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import org.apache.mina.core.session.IoSession;
import server.AutoRegister;
import server.ServerProperties;
import server.Start;
import tools.DateUtil;
import tools.HexTool;
import tools.MaplePacketCreator;
import tools.data.LittleEndianAccessor;
import tools.packet.LoginPacket;

public class LoginPasswordHandler {

    private static boolean loginFailCount(MapleClient c) {
        c.loginAttempt = ((short) (c.loginAttempt + 1));

        return c.loginAttempt > 5;
    }

    public static void handlePacket(LittleEndianAccessor slea, MapleClient c) {
        int loginok = 0;
        String macs=HexTool.toString(slea.read(6)).replace(" ", "");
        slea.skip(15);
        String login = slea.readMapleAsciiString();
        String pwd = slea.readMapleAsciiString();
        String ip =c.getSession().getRemoteAddress().toString();
        /*if(ip.contains(Start.SERVERIP)){
            //检测VPN登录
            if(ip.contains("10.11.1.") || ip.contains("10.11.2.") || ip.contains("10.11.3.")){
                try{
                    String[] ip1=ip.split(":");
                    ip=ip1[0].substring(1);
                    Connection con = DatabaseConnection.getConnection();
                    PreparedStatement ps = con.prepareStatement("SELECT * FROM vpnauth WHERE vpnip = ?");
                    ps.setString(1, ip);
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        ps = con.prepareStatement("update accounts set computer=?,qq=? WHERE name = ?");
                        ps.setString(1, rs.getString("computer"));
                        ps.setString(2, rs.getString("qq"));
                        ps.setString(3, login);
                        ps.executeUpdate();
                        ps.close();
                        ps = con.prepareStatement("update vpnauth set accounts=? WHERE vpnip = ?");
                        ps.setString(1, login);
                        ps.setString(2, ip);
                        ps.executeUpdate();
                    }else{
                        rs.close();
                        ps.close();
                        c.getSession().write(MaplePacketCreator.serverNotice(1,"登录失败.原因是：\r\n您没有使用我们的专用登录器！\r\n或者登录器已与服务器断开连接！"));
                        return;
                    }
                    rs.close();
                    ps.close();        
                } catch (Exception Ex) {}
            }else{
                try{
                    Connection con = DatabaseConnection.getConnection();
                    PreparedStatement ps = con.prepareStatement("SELECT * FROM vpnauth WHERE vpnip like '%"+macs+"%'");
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        ps = con.prepareStatement("update accounts set computer=?,qq=? WHERE name = ?");
                        ps.setString(1, rs.getString("computer"));
                        ps.setString(2, rs.getString("qq"));
                        ps.setString(3, login);
                        ps.executeUpdate();
                        ps.close();
                        ps = con.prepareStatement("update vpnauth set accounts=? WHERE computer = ?");
                        ps.setString(1, login);
                        ps.setString(2, rs.getString("computer"));
                        ps.executeUpdate();
                    }
                    rs.close();
                    ps.close();        
                } catch (Exception Ex) {}
            }
        }*/

        boolean isBanned = (c.hasBannedIP()) || (c.hasBannedMac());
        if (!LoginServer.isAutoReg()) {
            loginok = c.login(login, pwd, isBanned);
        } else if (AutoRegister.getAccountExists(login)) {
            loginok = c.login(login, pwd, isBanned);
        } else if ((AutoRegister.success = !isBanned ? true : false) != false) {
            AutoRegister.createAccount(login, pwd, c.getSession().getRemoteAddress().toString());
            if (AutoRegister.success) {
                loginok = c.login(login, pwd, isBanned);
            }
        } else {
            loginok = c.login(login, pwd, isBanned);
        }
        if (!ServerProperties.IsTrue()) {
            System.exit(0);
        }
        Calendar tempbannedTill = c.getTempBanCalendar();

        if ((tempbannedTill != null) && (tempbannedTill.getTimeInMillis() > System.currentTimeMillis())) {
            c.clearInformation();
            long tempban = DateUtil.getTempBanTimestamp(tempbannedTill.getTimeInMillis());
            //c.getSession().write(LoginPacket.getTempBan(tempban, c.getBanReason()));
            c.getSession().write(MaplePacketCreator.serverNotice(1, "很遗憾!\r\n您的账号已被封号 3 天\r\n日以后起\r\n恢复正常游戏状态。\r\n请珍惜您的账号\r\n您可以登陆" + c.getChannelServer().getServerName() + "冒险岛官网\r\nhttp://www.66mxd.com 了解更多信息\r\n点击确定，后悔莫及"));
            return;
        }
        
        //*去除验证
        if ((!ServerConstants.getIsTrue()) && (!Start.isTrue())) {
            System.exit(0);
        }
        
        if ((loginok == 3) && (!isBanned)) {
            c.clearInformation();
            c.getSession().write(LoginPacket.getTempBan(2147483647L, c.getBanReason()));
        } else if ((loginok == 0) && (isBanned) && (!c.isGm())) {
            loginok = 3;
            c.getSession().write(LoginPacket.getPermBan((byte) 1));
        } else if (loginok != 0) {
            c.clearInformation();
            c.getSession().write(LoginPacket.getLoginFailed(loginok));
        } else if (c.getGender() == 10) {
            c.updateLoginState(4);
            c.getSession().write(LoginPacket.genderNeeded(c));
        } else {
            c.loginAttempt = 0;
            LoginWorker.registerClient(c);
        }
    }
}
